package com.oneday.nuo.base.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.oneday.nuo.WebConfig;
import com.oneday.nuo.base.config.BaseService;
import com.oneday.nuo.base.dao.NuoUserRoleDAO;
import com.oneday.nuo.base.entity.NuoUserRoleEntity;
import com.oneday.nuo.base.exception.NuoException;
import com.oneday.nuo.base.service.NuoUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * (NuoUserRole)表服务实现类
 *
 * @author liushuai
 * @since 2021-03-13 23:37:57
 */
@Service("nuoUserRoleService")
public class NuoUserRoleServiceImpl extends BaseService<NuoUserRoleDAO, NuoUserRoleEntity> implements NuoUserRoleService {

    @Autowired
    private NuoUserRoleDAO nuoUserRoleDao;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveRoleUser(Map<String, Object> param) {
        String userId = (String) param.get("userId");
        List<String> roleIds = (List<String>) param.get("roleIds");
        if(StrUtil.isEmpty(userId)){
            throw  new NuoException("用户id不能为空");
        }
        LambdaQueryWrapper<NuoUserRoleEntity> wrapper = new LambdaQueryWrapper();
        wrapper.eq(NuoUserRoleEntity::getUserId,userId);
        nuoUserRoleDao.delete(wrapper);
        if(CollectionUtils.isNotEmpty(roleIds)){
            List<NuoUserRoleEntity> lists = new ArrayList<>();
            roleIds.forEach(res->{
                lists.add(NuoUserRoleEntity.builder()
                        .roleId(res)
                        .userId(userId)
                        .build());
            });
            this.saveBatch(lists);
        }
    }

    @Override
    public List<String> queryRoleIdsByUserId(String userId) {
        LambdaQueryWrapper<NuoUserRoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(NuoUserRoleEntity::getRoleId);
        wrapper.eq(NuoUserRoleEntity::getUserId,userId);
        List<NuoUserRoleEntity> nuoUserRoleEntities = nuoUserRoleDao.selectList(wrapper);
        if(CollectionUtils.isNotEmpty(nuoUserRoleEntities)){
            List<String> roleIds = nuoUserRoleEntities.stream().map(NuoUserRoleEntity::getRoleId).collect(Collectors.toList());
            return roleIds;

        }
        return null;
    }
}